package com.example.captcha.Controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.lang.Console;
import com.example.captcha.Model.captchaProperties;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class captchaController {
    private final static Long VAILD_TIME=1000*60*5L;
    @Autowired
private captchaProperties captchaProperties;
    @RequestMapping("/getCaptcha")
       public void  getCaptcha(HttpServletResponse response, HttpSession session){
        response.setCharacterEncoding("UTF-8");
        // 修正为正确的图片类型
        response.setContentType("image/jpeg");
        try {
            //定义图形验证码的长、宽、验证码字符数、干扰线宽度
            ShearCaptcha lineCaptcha= CaptchaUtil.createShearCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
            String code=lineCaptcha.getCode();
            System.out.println(code);
            session.setAttribute(captchaProperties.getSession().getCode(),code);
            session.setAttribute(captchaProperties.getSession().getDate(),new Date());
            lineCaptcha.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @RequestMapping("/check")
    public boolean check(String captcha,HttpSession session){
if(!StringUtils.hasLength(captcha)) {
    return false;
    }
String code= (String) session.getAttribute(captchaProperties.getSession().getCode());
Date date= (Date) session.getAttribute(captchaProperties.getSession().getDate());
if(captcha.equalsIgnoreCase(code)&&date!=null&&(System.currentTimeMillis()-date.getTime()<VAILD_TIME)){
    return true;
}
return false;
    }
}
